﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net.Mime;
using System.Net;
using System.Windows;

namespace inzDesktop
{
    class WPFEmailer
    {
        public string From { get; set; }
        public Dictionary<String,String> To { get; set; }
        public string User { get; set; }
        public string Password { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
        public string AttachmentPath { get; set; }
        public string Host { get; set; }
        public int Port { get; set; }
        public string CC { get; set; }
        public bool IsHtml { get; set; }
        public int SendUsing { get; set; } //0=Network, 1 = PickupDirectory, 2 = SpecifiedPickupDirectory
        public bool UseSSL { get; set; }
        public int AuthenticationMode { get; set; } //0 = No authentication, 1 = Plain Text, 2 = NTLM authentication

        // posłuży do anulowania wysylania
        public SmtpClient client;

        public WPFEmailer(string from,Dictionary<String, String> to, string user, string pass,
            string subject,string body,string attrchmentpath,string host,
            int port, string cc, bool ishtml, int sendusing, bool usessl, int authenticationmode)
        {
            
            this.From = from;
            this.To = to;
            this.User = user;
            this.Password = pass;
            this.Subject = subject;
            this.Body = body;
            this.AttachmentPath = attrchmentpath;
            this.Host = host;
            this.Port = port;
            this.CC = cc;
            this.IsHtml = ishtml;
            this.SendUsing = sendusing;
            this.UseSSL = usessl;
            this.AuthenticationMode = authenticationmode;

            this.client = new SmtpClient();
                 
        }
        public WPFEmailer()
            : this("", new Dictionary<String,String>(), "", "", "", "", "", "", 25, "", true, 0, true, 1)
        {}

        
        /// <summary>
        /// Funkcja wysyłająca email
        /// </summary>        
        /// <param name="pojedynczo">Określa czy wiadomosci bedą wysyłane pojedynczon</param>
        public int wyslij()
        {
            MailMessage mail = new MailMessage();
            // Nadawca
            mail.From = new MailAddress(this.From);

            // Odbiorcy
            foreach (KeyValuePair<String, String> odbiorcy in To)
            {
                //odbiorcy.Key
                
                try
                {
                    mail.To.Add(new MailAddress(odbiorcy.Value));
                }
                catch (FormatException ex)
                {
                    MessageBox.Show("Podano błędy adres e-mail.");
                }
            }

            // Tytuł
            mail.Subject = this.Subject;            
            
            // Treść wiadomości            
            mail.IsBodyHtml = this.IsHtml;

            // Gdy klient obsługuje html
            AlternateView avHtml = AlternateView.CreateAlternateViewFromString(this.Body, Encoding.UTF8, MediaTypeNames.Text.Html);

            // Gdy klient nie obsługuje html
            string tekst = "Musisz użyć klienta obsługującego html.";
            AlternateView avText = AlternateView.CreateAlternateViewFromString(tekst, Encoding.UTF8, MediaTypeNames.Text.Plain);

            mail.AlternateViews.Add(avHtml);
            mail.AlternateViews.Add(avText);

            // dodawanie załącznika
            if(!string.IsNullOrEmpty(this.AttachmentPath))
                mail.Attachments.Add(new Attachment(AttachmentPath));
            
            
            // haslo do serwera smtp
            client.Credentials = new NetworkCredential(this.User, this.Password);

            client.Port = this.Port;
            client.Host = this.Host;
            client.EnableSsl = this.UseSSL;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;

            client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
            
            // Wysyłanie synchroniczne
            try
            {
                client.SendAsync(mail, null);
                return 1;
            }
            catch (InvalidOperationException e)
            {
                MessageBox.Show("Nie określono serwera hosta","Błąd",MessageBoxButton.OK,MessageBoxImage.Error);
                client.SendAsyncCancel();
                return -1;
                
            }
            catch (SmtpException e)
            {
                MessageBox.Show("Nazwa serwera hosta nie została znaleziona", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);
                client.SendAsyncCancel();
                return -1;
            }
            catch (Exception e)
            {
                client.SendAsyncCancel();
                return -1;
            }
            
        }

        void client_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (e.Cancelled)
                {

                    MessageBox.Show("Wysyłanie zostało anulowane", "Informacja", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else if (e.Error != null)
                {
                    string error = String.Format("Błąd: {0}", e.Error.Message);
                    MessageBox.Show(error, "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);

                }
                //else
                //{
                  //  MessageBox.Show("Wiadomość została wysłana poprawnie", "Sukces", MessageBoxButton.OK, MessageBoxImage.Information);
                //}
        }
    }
}
